package com.example.demo.controller;

import com.example.demo.utils.AlertUtils;
import com.example.demo.utils.BigDecimalUtils;
import com.example.demo.utils.StageUtils;
import com.example.demo.utils.TextFieldUtils;
import com.example.demo.yjcx.BasePriceTypeEnum;
import com.example.demo.yjcx.dao.BasePriceDO;
import com.example.demo.yjcx.model.YJCalculateResult;
import com.example.demo.yjcx.service.BasePriceService;
import com.example.demo.yjcx.service.YJCalculateService;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;

import static com.example.demo.utils.AlertUtils.showAlert;

/**
 * @author linjingze
 * @date 2023/12/21 9:24 AM
 */
@Controller
public class PriceSearchController {

    @Autowired
    private BasePriceService basePriceService;

    @Autowired
    private YJCalculateService yjCalculateService;

    private Label tipLabel;
    public void showConfigView() {
        Stage dialogStage = new Stage();

        List<BasePriceDO> basePriceList = basePriceService.listBasePrice();
        Map<String, BasePriceDO> basePriceMap = CollectionUtils.emptyIfNull(basePriceList).stream()
                .collect(Collectors.toMap(BasePriceDO::getType, Function.identity()));

        // 创建GridPane作为布局
        GridPane grid = new GridPane();
        grid.setPadding(new Insets(10, 10, 10, 10));
        grid.setVgap(5);
        grid.setHgap(5);


        // 创建标签和输入框
        Label shippingCostLabel = new Label("NYC海运费:");
        BasePriceDO nychyf = basePriceMap.computeIfAbsent(BasePriceTypeEnum.NYC_HYF.name(), BasePriceDO::new);
        TextField shippingCostField = getDecimalTextField(nychyf, BasePriceDO::getPrice);

        Label chiLabel = new Label("CHI海运费:");
        BasePriceDO chihyf = basePriceMap.computeIfAbsent(BasePriceTypeEnum.CHI_HYF.name(), BasePriceDO::new);
        TextField chiField = getDecimalTextField(chihyf, BasePriceDO::getPrice);

        Label houLabel = new Label("HOU海运费:");
        BasePriceDO houhyf = basePriceMap.computeIfAbsent(BasePriceTypeEnum.HOU_HYF.name(), BasePriceDO::new);
        TextField houField = getDecimalTextField(houhyf, BasePriceDO::getPrice);

        BasePriceDO hl = basePriceMap.computeIfAbsent(BasePriceTypeEnum.HL.name(), BasePriceDO::new);
        Label exchangeRateLabel = new Label("汇率:");
        TextField exchangeRateField = getDecimalTextField(hl, BasePriceDO::getPrice);

        Label calculationBaseLabel = new Label("以多少核算:");
        BasePriceDO hs = basePriceMap.computeIfAbsent(BasePriceTypeEnum.HS.name(), BasePriceDO::new);
        TextField calculationBaseField = getDecimalTextField(hs, BasePriceDO::getPrice);

        // 创建提交按钮
        Button submitButton = new Button("保存");

        // 将控件添加到布局中
        grid.add(shippingCostLabel, 0, 0);
        grid.add(shippingCostField, 1, 0);

        grid.add(chiLabel, 0, 1);
        grid.add(chiField, 1, 1);
        grid.add(houLabel, 0, 2);
        grid.add(houField, 1, 2);
        grid.add(exchangeRateLabel, 0, 3);
        grid.add(exchangeRateField, 1, 3);
        grid.add(calculationBaseLabel, 0, 4);
        grid.add(calculationBaseField, 1, 4);
        grid.add(submitButton, 1, 5);

        // 设置按钮点击事件（按需实现逻辑）
        submitButton.setOnAction(event -> {
            String shippingCost = shippingCostField.getText();
            String chi = chiField.getText();
            String hou = houField.getText();
            String exchangeRate = exchangeRateField.getText();
            String calculationBase = calculationBaseField.getText();

            if (StringUtils.isBlank(shippingCost) ||
                    StringUtils.isBlank(exchangeRate) ||
                    StringUtils.isBlank(chi) ||
                    StringUtils.isBlank(hou) ||
                    StringUtils.isBlank(calculationBase)) {
                showAlert("请填写信息");
                return;
            }
            nychyf.setPrice(shippingCost);
            houhyf.setPrice(hou);
            chihyf.setPrice(chi);
            hl.setPrice(exchangeRate);
            hs.setPrice(calculationBase);
            basePriceService.upsertBasePrice(Arrays.asList(nychyf, chihyf, houhyf, hl, hs));
            dialogStage.close(); // 关闭对话框
            AlertUtils.showAlert("保存成功");
        });

        // 设置场景和舞台
        Scene scene = new Scene(grid);
        dialogStage.initModality(Modality.WINDOW_MODAL);
        dialogStage.initOwner(StageUtils.stage);
        dialogStage.setTitle("运价信息配置");

        dialogStage.setScene(scene);
        dialogStage.setWidth(400);
        dialogStage.show();


    }

    private TextField getDecimalTextField(BasePriceDO value, Function<BasePriceDO, String> v) {
        TextField decimalTextField = TextFieldUtils.createDecimalTextField();
        if (value != null) {
            decimalTextField.setText(v.apply(value));
        }
        return decimalTextField;
    }

    public void showPriceSearchView() {
        Stage dialogStage = new Stage();
        VBox layout = new VBox(10);
        layout.setPadding(new Insets(15, 12, 15, 12));

        // 创建HBox布局用于存放搜索框和按钮
        HBox searchBox = new HBox();
        searchBox.setSpacing(10);
        tipLabel = new Label();
        // 创建仓库标签和搜索框
        Label warehouseLabel = new Label("仓库:");
        TextField searchField = new TextField();

        // 创建搜索按钮
        Button searchButton = new Button("查询");

        // 将标签、搜索框和按钮添加到HBox布局
        searchBox.getChildren().addAll(warehouseLabel, searchField, searchButton);

        // 创建表格视图，用于显示搜索结果
        TableView<YJCalculateResult> tableView = new TableView<>();
        TableColumn<YJCalculateResult, String> areaCol = getTableColumn("从哪里出");
        areaCol.setCellValueFactory(cellData -> cellData.getValue().area());

        TableColumn<YJCalculateResult, String> dbjgCol = getTableColumn("单板价格");
        dbjgCol.setCellValueFactory(cellData -> cellData.getValue().dbjg());

        TableColumn<YJCalculateResult, String> zcjgCol = getTableColumn("整车价格");
        zcjgCol.setCellValueFactory(cellData -> cellData.getValue().zcjg());

        TableColumn<YJCalculateResult, String> lfcbCol = getTableColumn("不包税");
        lfcbCol.setCellValueFactory(cellData -> cellData.getValue().lfcb());

        TableColumn<YJCalculateResult, String> bsgjcbCol = getTableColumn("包税");
        bsgjcbCol.setCellValueFactory(cellData -> cellData.getValue().bsgjcb());


        tableView.getColumns().addAll(bsgjcbCol, lfcbCol, areaCol, dbjgCol, zcjgCol);

        tableView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
        searchField.setOnAction(e -> {
            search(searchField, tableView, layout);
        });
        // 定义搜索按钮的事件处理逻辑
        searchButton.setOnAction(event -> {
            search(searchField, tableView, layout);
        });

        // 将HBox布局和TableView添加到VBox布局
        layout.getChildren().addAll(searchBox, tableView);


        // 设置舞台和场景
        Scene scene = new Scene(layout);
        dialogStage.initOwner(StageUtils.stage);
        dialogStage.setScene(scene);
        dialogStage.setWidth(800);
        dialogStage.setHeight(270);
        dialogStage.setTitle("运价查询");
        dialogStage.show();

    }

    private static TableColumn<YJCalculateResult, String> getTableColumn(String name) {
        TableColumn<YJCalculateResult, String> bsgjcbCol = new TableColumn<>();
        HBox columnHeaderHBox = new HBox();
        Label columnHeaderLabel = new Label(name); // 列标题文本
        columnHeaderHBox.getChildren().add(columnHeaderLabel);
        columnHeaderHBox.setAlignment(Pos.CENTER_LEFT); // 设置HBox内部对齐为左对齐
        bsgjcbCol.setGraphic(columnHeaderHBox); // 设置列标题的图形
        return bsgjcbCol;
    }

    private void search(TextField searchField, TableView<YJCalculateResult> tableView, VBox layout) {
        String text = searchField.getText();
        if (StringUtils.isBlank(text)) {
            showAlert("请填写仓库");
            return;
        }
        tipLabel.setText("");
        List<YJCalculateResult> resultList = null;
        boolean bsIsGt20 = false;
        try {
            resultList = yjCalculateService.calculate(text.toUpperCase());
            bsIsGt20 = resultList.stream().anyMatch(s -> BigDecimalUtils.greater(s.getBsgjcb(), new BigDecimal(20)));
        } catch (Exception e) {
            e.printStackTrace();
            showAlert(e.getMessage());
            resultList = Collections.emptyList();
        }
        ObservableList<YJCalculateResult> data = FXCollections.observableArrayList(
                resultList
        );
        tableView.setItems(data);
        if (!tableView.getItems().isEmpty()) {
            String tipMsg = "报价不含附加费，请自行参考价格表，货物自交九方宁波仓；私人地址无卸货平台+USD150。";
            if (bsIsGt20) {
                tipMsg = tipMsg + "\r\n" + "偏点小方数建议海派，末端派送时效预计会拉长至2周及以上。";
            }
            tipLabel.setText(tipMsg);
            tipLabel.setWrapText(true); // 使文本在达到标签宽度时自动换行
            ObservableList<Node> children = layout.getChildren();
            if (!children.contains(tipLabel)) {
                children.add(tipLabel);
            }

        }
    }
}
